#include "xglog.h"
#include <unistd.h>
enum class TimeGap
{
  GAP_SCOND,
  GAP_MINUTE,
  GAP_HOUR,
  GAP_DAY,
};
class RollByTimeSink : public xglog::LogSink
{
public:
  RollByTimeSink(const std::string &basename, TimeGap gap_type) : _basename(basename)
  {
    switch (gap_type)
    {
    case TimeGap::GAP_SCOND:
      _gap_size = 1;
      break;
    case TimeGap::GAP_MINUTE:
      _gap_size = 60;
      break;
    case TimeGap::GAP_HOUR:
      _gap_size = 3600;
      break;
    case TimeGap::GAP_DAY:
      _gap_size = 3600 * 24;
      break;
    }
    _cur_gap = xglog::util::Date::now() / _gap_size; // 获取当前是第几个时间段
    std::string filename = createNewFile();
    xglog::util::File::createDirctory(xglog::util::File::path(filename));
    _ofs.open(filename, std::ios::binary | std::ios::app);
    assert(_ofs.is_open());
  }
  // 将日志消息写入到文件，判断当前时间是否是当前文件的时间段，不是则切换文件
  void log(const char *data, size_t len)
  {
    time_t cur = xglog::util::Date::now();
    if ((cur / _gap_size) != _cur_gap)
    {
      _ofs.close();
      std::string filename = createNewFile();
      _ofs.open(filename, std::ios::binary | std::ios::app);
      assert(_ofs.is_open());
    }
    _ofs.write(data, len);
    assert(_ofs.good());
  }

private:
  std::string createNewFile()
  {
    // 获取系统时间，以时间来构造文件扩展名
    time_t t = xglog::util::Date::now();
    struct tm lt;
    localtime_r(&t, &lt);
    std::stringstream filename;
    filename << _basename;
    filename << lt.tm_year + 1900;
    filename << lt.tm_mon + 1;
    filename << lt.tm_mday;
    filename << lt.tm_hour;
    filename << lt.tm_min;
    filename << lt.tm_sec;
    filename << ".log";
    return filename.str();
  }

private:
  std::string _basename;
  std::ofstream _ofs;
  size_t _cur_gap;  // 当前是第几个时间段
  size_t _gap_size; // 时间间隔
};